<template>
  <div class="form-container">
    <a-form
      ref="formRef"
      :disabled="formDisable"
      :model="formState"
      layout="horizontal"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      :rules="formRules"
    >
      <a-row :gutter="24">
        <!-- 第一列 -->
        <a-col :span="12">
          <a-form-item label="项目名称" name="projectName">
            <a-input v-model:value="formState.projectName" placeholder="请输入项目名称" />
          </a-form-item>
          <a-form-item label="项目类型" name="projectType">
            <a-select v-model:value="formState.projectType" :options="options_projectType" placeholder="请选择项目类型" />
          </a-form-item>
          <a-form-item label="实施阶段" name="implementationStage">
            <a-select v-model:value="formState.implementationStage" placeholder="请选择实施阶段" :options="options_stage" />
          </a-form-item>
          <a-form-item name="projectFile" label="项目文件" extra="上传文件，支持格式：.doc、.docx">
            <a-upload v-model:fileList="formState.projectFile" name="logo" accept=".doc,.docx" action="/upload.do" list-type="picture">
              <a-button>
                <template #icon><UploadOutlined /></template>
                点击上传文件
              </a-button>
            </a-upload>
          </a-form-item>
          <a-form-item label="计划检查开始时间" name="plannedInspectionStartTime">
            <a-date-picker v-model:value="formState.plannedInspectionStartTime" style="width: 100%" placeholder="请选择计划巡视开始时间" />
          </a-form-item>
          <a-form-item label="计划检查结束时间" name="plannedInspectionEndTime">
            <a-date-picker v-model:value="formState.plannedInspectionEndTime" style="width: 100%" placeholder="请选择计划检查结束时间" />
          </a-form-item>
        </a-col>

        <!-- 第二列 -->
        <a-col :span="12">
          <a-form-item label="项目经理" name="projectManager">
            <a-input v-model:value="formState.projectManager" placeholder="请选择项目经理">
              <template #addonAfter>
                <div @click="openModalClick_UserByDept">
                  <MenuUnfoldOutlined />
                </div>
              </template>
            </a-input>
            <UserSelect ref="userSelectByDeptRef" @change="onChange_userByDept" />
          </a-form-item>
          <a-form-item label="部门人员" name="departmentUser">
            <a-input v-model:value="formState.departmentUser" placeholder="请选择部门人员">
              <template #addonAfter>
                <div @click="openModalClick_User">
                  <MenuUnfoldOutlined />
                </div>
              </template>
            </a-input>
            <UserSelect ref="userSelectRef" multiple @change="onChange_user" />
          </a-form-item>
          <a-form-item label="项目部门" name="projectDepartment">
            <a-input v-model:value="formState.projectDepartment" placeholder="请选择项目部门">
              <template #addonAfter>
                <div @click="openModalClick_Department">
                  <MenuUnfoldOutlined />
                </div>
              </template>
            </a-input>
            <DepartmentSelect ref="departmentSelectRef" @change="onChange_department" />
          </a-form-item>
          <a-form-item label="项目实施单位" name="projectImplementationUnit">
            <a-input v-model:value="formState.projectImplementationUnit" placeholder="请输入项目实施单位" />
          </a-form-item>
          <a-form-item label="项目地点" name="projectLocation">
            <a-input v-model:value="formState.projectLocation" placeholder="请输入项目地点" />
          </a-form-item>
          <a-form-item label="检查牵头部门" name="inspectionLeadDepartment">
            <a-input v-model:value="formState.inspectionLeadDepartment" placeholder="请输入检查牵头部门" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </div>
</template>

<script setup lang="ts">
  import { reactive, ref, onMounted, defineProps } from 'vue';
  import { FormInstance } from 'ant-design-vue';
  import UserSelectModal from '/@/components/Form/src/cyj/components/modal/UserSelectModal.vue';
  import UserSelectByDepModal from '/@/components/Form/src/cyj/components/modal/UserSelectByDepModal.vue';
  import DeptSelectModal from '/@/components/Form/src/cyj/components/modal/DeptSelectModal.vue';
  import { useModal } from '/@/components/Modal';
  import { MenuUnfoldOutlined } from '@ant-design/icons-vue';
  import DepartmentSelect from '/@/components/Form/src/cyj/components/DepartmentSelectNative.vue';
  import UserSelect from '/@/components/Form/src/cyj/components/UserSelectNative.vue';

  /**部门选择 */
  const departmentSelectRef = ref();
  const openModalClick_Department = () => {
    departmentSelectRef.value.openModalClick();
  };
  const onChange_department = (value, options) => {
    console.log('value, options', value, options);
    formState.value.projectDepartment = options.map((item) => item.department_name);
  };

  /**人员选择 */
  const userSelectRef = ref();

  const openModalClick_User = () => {
    userSelectRef.value.openModalClick();
  };

  const onChange_user = (value, options) => {
    console.log('value, options', value, options);
    formState.value.departmentUser = options.map((item) => item.employee_name);
  };
  /**人员选择 */

  /**部门人员选择 */
  const userSelectByDeptRef = ref();

  const openModalClick_UserByDept = () => {
    userSelectByDeptRef.value.openModalClick();
  };

  const onChange_userByDept = (value, options) => {
    console.log('value, options', value, options);
    formState.value.projectManager = options.map((item) => item.employee_name);
  };
  /**部门人员选择 */

  defineProps({
    formDisable: {
      type: Boolean,
      default: false,
    },
  });

  // 表单引用
  const formRef = ref<FormInstance | null>(null);

  // 表单数据
  const formState = ref({
    projectName: '',
    implementationStage: '',
    projectType: '',
    projectImplementationUnit: '',
    projectLocation: '',
    projectManager: '',
    departmentUser: '',
    projectDepartment: '',
    inspectionLeadDepartment: '',
    plannedInspectionStartTime: '',
    plannedInspectionEndTime: '',
  });

  // 项目类型
  const options_projectType = ref([
    {
      value: '建筑工程',
      label: '建筑工程',
    },
    {
      value: '软件开发',
      label: '软件开发',
    },
    {
      value: '交通工程',
      label: '交通工程',
    },
  ]);

  // 项目阶段
  const options_stage = ref([
    {
      value: '筹备阶段',
      label: '筹备阶段',
    },
    {
      value: '实施阶段',
      label: '实施阶段',
    },
    {
      value: '验收阶段',
      label: '验收阶段',
    },
  ]);

  // 必填字段列表 - 可根据实际需求调整哪些字段需要必填校验
  const requiredFields: Array<keyof typeof formState.value> = [
    'projectName',
    'projectType',
    'implementationStage',
    'projectImplementationUnit',
    'projectLocation',
    'departmentUser',
    'projectDepartment',
    'inspectionLeadDepartment',
    'projectManager',
  ];

  // 生成表单校验规则
  const formRules = reactive<Record<string, any[]>>({});

  // 初始化表单规则
  onMounted(() => {
    requiredFields.forEach((field) => {
      formRules[field] = [
        {
          required: true,
          message: `${getFieldLabel(field)}不能为空`,
          trigger: field.includes('Time') ? 'change' : 'blur',
        },
      ];
    });
  });

  // 获取字段标签文本（用于错误提示）
  const getFieldLabel = (field: string): string => {
    const labelMap: Record<string, string> = {
      projectName: '项目名称',
      projectType: '项目类型',
    };
    return labelMap[field] || field;
  };

  // 统一的表单校验方法
  const validateForm = async (): Promise<boolean> => {
    if (!formRef.value) return false;
    try {
      await formRef.value.validate();
      return Promise.resolve(true); // 校验通过
    } catch (error) {
      return Promise.reject(false); // 校验失败
    }
  };

  // 获取表单数据
  const getFormData = (): typeof formState.value => {
    return { ...formState.value };
  };

  // 重置表单
  const handleReset = () => formRef?.value?.resetFields();

  // 暴露方法给父组件
  defineExpose({
    validateForm, // 校验表单方法
    getFormData, // 获取表单数据方法
    handleReset, // 重置表单方法
    formState: formState.value,
  });
</script>

<style scoped>
  .form-container {
    /* padding: 20px; */
    background-color: #fff;
    border-radius: 4px;
    /* box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); */
  }

  .form-actions {
    margin-top: 20px;
    text-align: right;
  }
</style>
